from flask import Flask, request, jsonify
from marshmallow import Schema, fields, validate, ValidationError

app = Flask(__name__)


# 定义验证 schema
class ProductSchema(Schema):
    name = fields.Str(required=True, validate=validate.Length(min=1, max=100))
    price = fields.Float(required=True, validate=validate.Range(min=0))
    stock = fields.Int(required=True, validate=validate.Range(min=0))
    category = fields.Str(validate=validate.OneOf(["electronics", "clothing", "books"]))


# 初始化 schema 实例
product_schema = ProductSchema()


@app.route('/product', methods=['POST'])
def add_product():
    try:
        # 验证并反序列化数据
        data = product_schema.load(request.json)

        # 验证通过，处理数据
        return jsonify({
            "message": "Product added successfully",
            "data": data
        }), 201

    except ValidationError as err:
        # 验证失败，返回错误信息
        return jsonify({"errors": err.messages}), 400


@app.route('/search', methods=['GET'])
def search_products():
    try:
        # 验证查询参数
        args = product_schema.load(request.args.to_dict(), partial=True)

        # 处理查询
        return jsonify({
            "message": "Search completed",
            "filters": args
        })

    except ValidationError as err:
        return jsonify({"errors": err.messages}), 400


if __name__ == '__main__':
    app.run(debug=True)
